package com.fliad.ai.controller;

import cn.hutool.core.util.IdUtil;
import com.fliad.ai.entity.AiKnowledge;
import com.fliad.ai.service.AiKnowledgeService;
import org.noear.snack.ONode;
import org.noear.solon.ai.rag.repository.InMemoryRepository;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Result;
import org.noear.wood.DbContext;
import org.noear.wood.annotation.Db;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 知识库控制器
 */
public class AiKnowledgeController {
    @Db
    DbContext db;

    @Inject
    AiKnowledgeService aiKnowledgeService;

    // 获取向量数据库类型列表
    @Get
    @Mapping("/repositoryTypes")
    public Result<List<String>> getRepositoryTypes() {
        List<String> list = new ArrayList<>();
        list.add(InMemoryRepository.class.getSimpleName());
        return Result.succeed(list);
    }

    // 创建知识库
    @Post
    @Mapping("")
    public Result<Boolean> create(@Body AiKnowledge knowledge) throws SQLException {
        knowledge.setId(IdUtil.getSnowflakeNextId());
        knowledge.setCreated(new Date());
        knowledge.setModified(new Date());
        return Result.succeed(aiKnowledgeService.create(knowledge));
    }

    // 查询单个知识库
    @Get
    @Mapping("/{id}")
    public Result<AiKnowledge> get(@Path("id") Long id) throws SQLException {
        return Result.succeed(aiKnowledgeService.get(id));
    }

    // 查询知识库列表
    @Get
    @Mapping("")
    public Result<List<AiKnowledge>> list(String title, String vectorStoreType) throws SQLException {
        return Result.succeed(aiKnowledgeService.list(title, vectorStoreType));
    }

    // 删除知识库
    @Delete
    @Mapping("/{id}")
    public Result<Boolean> delete(@Path("id") Long id) throws SQLException, IOException {
        return Result.succeed(aiKnowledgeService.delete(id));
    }

    @Get
    @Mapping("/search/{id}")
    public Result<ONode> search(@Path("id") Long id, @Param String keyword) throws SQLException, Exception {
        return Result.succeed(ONode.newObject().set("searchResult", ONode.load(aiKnowledgeService.search(id, keyword))));
    }

}
